package com.titanium.java;

import org.junit.Test;

import java.util.*;

/**
 *@program: JavaSenior
 *@description:
 *@author: renfei.huang
 *@create: 2021-10-13 13:28
 */
public class TreeMapTest {

    //向TreeMap中添加key-value ,要求key必须是同一个类创建的对象
    //因为要按照key进行排序：自然排序，定制排序

    @Test
    public  void test1(){

        TreeMap treeMap = new TreeMap();

        User u1 = new User("Tom", 12);
        User u2 = new User("Jack", 9);
        User u3 = new User("LiShan", 16);
        User u4 = new User("Anni", 15);
        User u5 = new User("ShanMu", 22);

        treeMap.put(u1,94);
        treeMap.put(u2,90);
        treeMap.put(u3,77);
        treeMap.put(u4,98);
        treeMap.put(u5,100);

        Set entrySet = treeMap.entrySet();
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            System.out.println(entry.getKey() +"------------------>"+entry.getValue());
        }

    }


    //定制排序
    @Test
    public  void test2(){


        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 =(User) o1;
                    User u2 =(User) o2;
                    return  -Integer.compare(u1.getAge(),u2.getAge());
                }
                throw new RuntimeException("输入的类型不一致");
            }
        });

        User u1 = new User("Tom", 12);
        User u2 = new User("Jack", 9);
        User u3 = new User("LiShan", 16);
        User u4 = new User("Anni", 15);
        User u5 = new User("ShanMu", 22);

        treeMap.put(u1,94);
        treeMap.put(u2,90);
        treeMap.put(u3,77);
        treeMap.put(u4,98);
        treeMap.put(u5,100);

        Set entrySet = treeMap.entrySet();
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            System.out.println(entry.getKey() +"------------------>"+entry.getValue());
        }

    }



}
